package net.cyan.commons.pool;

import net.cyan.commons.aop.proxy.*;

import java.lang.reflect.Method;


/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2007</p>
 * <p>Company: </p>
 *
 * @author ccs
 * @version 1.0
 */

public class ProxyObjectProxy extends DelegateProxy
{
    private static ClassProxy proxy;

    static
    {
        proxy = new ClassProxy();
        proxy.setMethodProxys(new ProxyObjectProxy());
        proxy.addVariable("obj", ClassProxy.SELFTYPE, true);
        proxy.addVariable("closed", boolean.class, false);
        proxy.addInterface(ProxyObject.class);
    }

    private ProxyObjectProxy()
    {
        super("obj");
    }

    protected void generateBody(StringBuilder buffer, Method method, String[] parameterNames, Class c,
                                ClassGenerateContext context)
    {
        if (method.getDeclaringClass() == ProxyObject.class)
        {
            buffer.append("closed=true;");
        }
        else
        {
            buffer.append("if(closed)\n");
            buffer.append("throw new RuntimeException(\"object is closed\");\n");
            super.generateBody(buffer, method, parameterNames, c, context);
        }
    }

    @SuppressWarnings("unchecked")
    public static <E> E create(E obj) throws Exception
    {
        Class c;
        if (obj instanceof PoolObject)
            c = ((PoolObject) obj).getRealClass();
        else
            c = obj.getClass();
        return (E) proxy.createObject(c, obj);
    }
}